package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Map;

//过滤器是要实现Filter接口的
//如果在过滤器上加了@Component或者@Configuration的注解，是不需要在启动类上@ServletComponentScan加这个注解的
@Component
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURL().toString();
        if (url.contains("/login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = request.getHeader("token");
        Map<String, Object> jwt = JwtUtils.parseJwt(token);
        if (ObjectUtils.isEmpty(token) || jwt == null){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //在在线程上获取用户的id
        CurrentHolder.set((Integer) jwt.get("id"));

        filterChain.doFilter(servletRequest,servletResponse);
        //执行完，释放资源
        CurrentHolder.remove();
    }
}
